package chapter8.Encapsulation;

/*不能随意查看人的年龄，工资等信息，并对设置的年龄进行合理的验证。
 年龄合理就设置，否则给默认
* */
public class Encapsulation01 {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("jack");
        person.setAge(20);
        person.setSalary(20000);
        System.out.println(person.info());
        Person smith = new Person("smith", 200, 20000);
        System.out.println(smith.info());

    }
}

class Person {
    public String name;//名字公开
    private int age;//私密
    private double salary;//私密

    public Person() {
    }
  //有三个属性的构造器重载，防止使用构造器漏洞，应该与set方法结合
    public Person(String name, int age, double salary) {
      setName(name);
      setAge(age);
      setSalary(salary);
    }

    //Alt+insert 自动生成Get和Set方法
    public String getName() {
        return name;
    }

    public void setName(String name) {
        //设置名字时进行校验
        if (name.length() > 2 && name.length() <= 6){
            this.name = name;}
        else {
            System.out.println("输入的名字有误。需要2-6个字符");
            this.name = "张三";
        }
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age > 1 && age <= 120) {
            this.age = age;
        } else {
            this.age = 18;
            System.out.println("输入的年龄有误，默认年龄18");
        }
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public String info() {
        return "name= " + name + "age=" + age + "sal=" + salary;
    }
}